// OrderService.java
package com.estore.model;

import com.estore.service.ProductService;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单服务类，负责订单相关的业务逻辑
 */
public class OrderService {

    // 存储所有订单
    private final Map<String, Order> orders = new ConcurrentHashMap<>();

    // 订单ID生成器
    private final AtomicLong orderIdGenerator = new AtomicLong(System.currentTimeMillis());

    private final ProductService productService;

    // 模拟当前用户ID

    public OrderService(ProductService productService) {
        this.productService = productService;
    }

    /**
     * 创建订单
     * @param userId 用户ID
     * @param cartItems 购物车商品映射
     * @return 创建的订单对象
     */
    public Order createOrder(String userId, Map<String, Integer> cartItems) {
        synchronized (this) { // 确保订单创建的原子性
            if (cartItems == null || cartItems.isEmpty()) {
                throw new IllegalArgumentException("购物车不能为空");
            }

            // 验证库存
            for (Map.Entry<String, Integer> entry : cartItems.entrySet()) {
                String productId = entry.getKey();
                int quantity = entry.getValue();

                Product product = productService.findProductById(productId);
                if (product == null) {
                    throw new IllegalArgumentException("商品ID %s 不存在".formatted(productId));
                }

                if (product.getStock() < quantity) {
                    throw new IllegalArgumentException("商品 %s 库存不足".formatted(product.getName()));
                }
            }

            // 计算总价
            double totalPrice = 0.0;
            for (Map.Entry<String, Integer> entry : cartItems.entrySet()) {
                String productId = entry.getKey();
                int quantity = entry.getValue();
                Product product = productService.findProductById(productId);
                totalPrice += product.getPrice() * quantity;
            }

            // 生成订单ID
            String orderId = "ORDER-%d".formatted(orderIdGenerator.incrementAndGet());

            // 创建订单
            Order order = new Order(orderId, userId, new HashMap<>(cartItems), totalPrice);
            orders.put(orderId, order);

            return order;
        }
    }


/**
 * 更新订单状态
 * @param orderId 订单ID
 * @param status 新的状态
 * @return 更新后的订单对象
 */
public Order updateOrderStatus(String orderId, Order.OrderStatus status) {
    Order order = orders.get(orderId);
    if (order == null) {
        return null;
    }

    order.setStatus(status);
    saveData(); // 添加数据持久化调用
    return order;
}


    /**
     * 根据订单ID查找订单
     * @param orderId 订单ID
     * @return 订单对象，如果不存在返回null
     */
    public Order findOrderById(String orderId) {
        return orders.get(orderId);
    }

    /**
     * 获取用户所有订单
     * @return 订单列表
     */
    public List<Order> getAllOrders() {
        return new ArrayList<>(orders.values());
    }

    /**
     * 根据用户ID查找订单
     * @param userId 用户ID
     * @return 用户的订单列表
     */
    public List<Order> getOrdersByUserId(String userId) {
        List<Order> userOrders = new ArrayList<>();
        for (Order order : orders.values()) {
            if (order.getUserId().equals(userId)) {
                userOrders.add(order);
            }
        }
        return userOrders;
    }

    /**
     * 根据状态筛选订单
     * @param status 订单状态
     * @return 符合条件的订单列表
     */
    public List<Order> getOrdersByStatus(Order.OrderStatus status) {
        List<Order> result = new ArrayList<>();
        for (Order order : orders.values()) {
            if (order.getStatus() == status) {
                result.add(order);
            }
        }
        return result;
    }

    /**
     * 根据用户ID和状态筛选订单
     * @param userId 用户ID
     * @param status 订单状态
     * @return 符合条件的订单列表
     */
    public List<Order> getOrdersByUserIdAndStatus(String userId, Order.OrderStatus status) {
        List<Order> result = new ArrayList<>();
        for (Order order : orders.values()) {
            if (order.getUserId().equals(userId) && order.getStatus() == status) {
                result.add(order);
            }
        }
        return result;
    }

    /**
 * 从文件加载订单数据
 */
public synchronized void loadData(){
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("orders.dat"))) {
        Map<String, Order> loadedOrders = (Map<String, Order>) ois.readObject();
        orders.clear();
        orders.putAll(loadedOrders);

        // 更新订单ID生成器，确保新订单ID不会重复
        long maxId = loadedOrders.values().stream()
            .map(Order::getOrderId)
            .filter(id -> id.startsWith("ORDER-"))
            .map(id -> id.substring(6))
            .mapToLong(Long::parseLong)
            .max()
            .orElse(0L);

        if (maxId > 0) {
            orderIdGenerator.set(maxId);
        }

        System.out.println("订单数据已从 orders.dat 加载");
    } catch (FileNotFoundException e) {
        System.out.println("订单数据文件不存在，将创建新的数据文件");
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("加载订单数据时出错: %s%n", e.getMessage());
    }
}

/**
 * 保存订单数据到文件
 */

public void saveData() {
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("orders.dat"))) {
        oos.writeObject(orders);
        System.out.println("订单数据已保存到 orders.dat");
    } catch (IOException e) {
        System.err.printf("保存订单数据时出错: %s%n", e.getMessage());
        e.printStackTrace(); // 打印完整的堆栈跟踪以帮助调试
    }
}
}
